<template>
  <!--<e-modal v-model:show="showDrawer" :width="380" title="代码生成" @ok="handleOk">
    <e-dict-input code="#gen_module" @update:value="(value) => (genData = { ...genData, ...value })" />
    <e-form v-model:model-value="genData" :instance="GenModule" :is-modal="false" />
  </e-modal>-->
  <e-form ref="formRef" v-bind="formProps" v-model:show="isShow" :before-submit="handleGenSubmit" ok-btn="预览" title="生成代码">
    <n-form-item label="生成文件">
      <e-dict-input
        v-model:value="checkedFileTypes"
        component="checkbox"
        multiple
        code="#gen_template"
        :query-params="{ templateType: 'default' }"
        @show="checkedFileTypeShowHandler"
      />
    </n-form-item>
    <template #bottom>
      <n-form-item label-placement="left" label="模块选择" :show-feedback="false">
        <e-dict-input
          code="#gen_module"
          style="width: 200px"
          @update:value="handleGenModuleTempChange"
          @show="
            (_, opts) => {
              console.log('opts ---> ', opts)
              const { dictCode: modelId } =
                opts?.findLast((dict) => {
                  return currTable?.name?.indexOf(`${dict.dictCode}_`) === 0
                }) || {}
              modelId && handleGenModuleTempChange(modelId)
            }
          "
        />
      </n-form-item>
    </template>
  </e-form>
</template>

<script setup lang="ts">
  // import { SaveRolePermissionParams, SysRoleApi } from '../model'
  import GenModule, { GeneratorData } from '@/views/gen/module/model'
  import { FormatFormData } from '@/components/ext/types'
  import GenTable, { GeneratorApi, GenPreviewFile, GenPreviewProps } from '@/views/gen/table/model'
  import { usePanel } from '@/components/ext'
  import { useDrawer } from '@/hooks/useDrawer'
  import { UseDrawerExpose } from '@/hooks/useDrawer/types'
  import { DictData, DictInputValues } from '@/components/ext/input/types'

  const {
    refs: { formRef },
    commProps: { formProps }
  } = usePanel(GenModule)

  const { isShow, data: currTable, open, close } = useDrawer<GenTable>()

  defineExpose<UseDrawerExpose<GenPreviewProps>>({
    open,
    close
  })

  // const currTable = ref<Model>()

  // 初始化表单数据的引用，用于存储生成的代码数据
  // const genData = ref<IFormData<GenModule>>({})

  // 定义允许勾选的文件类型数组，用于代码生成时选择不同的文件模板
  const checkedFileTypes = ref<string[]>([])

  const checkedFileTypeShowHandler = (_?: DictInputValues, options?: DictData[]) => {
    checkedFileTypes.value = options?.map((item) => item.dictCode) || []
  }

  const emits = defineEmits<{
    (e: 'ok', files: GenPreviewFile[], name: string): void
  }>()

  const handleGenSubmit: FormatFormData<GenModule> = async () => {
    // console.log('currTable.value ---> ', currTable.value)
    // const module = genData.value
    const { summary } = currTable.value!
    // const javaFileName = upperFirst(camelCase(tableName))
    // const moduleName = camelCase(tableName.substring(tableName.indexOf('_') + 1))
    // const getOutFileName = (type: string, pkg: string) => {
    //   // console.log('webFileName --> ', moduleName)
    //   // console.log('javaFileName --> ', javaFileName)
    //   let fileName = `${module.moduleCode}/${moduleName}/`
    //   const filePath = pkg.replaceAll('.', '/')
    //   switch (type) {
    //     case 'entity':
    //       fileName += `${filePath}/${javaFileName}.java`
    //       break
    //     case 'mapperXml':
    //       fileName += `${filePath}/${javaFileName}Mapper.xml`
    //       break
    //     case 'webList':
    //       fileName += `web/${filePath}/index.vue`
    //       break
    //     case 'webModel':
    //       fileName += `web/${filePath}/model.ts`
    //       break
    //     default:
    //       fileName += `${filePath}/${javaFileName}${upperFirst(type)}.java`
    //       break
    //   }
    //   return fileName.replaceAll('{module}', moduleName)
    // }
    // const data: GeneratorData = {
    //   tableId: currTable.value?.id,
    //   files: checkedFileTypes.value.map((fName) => {
    //     const item = fName.replace('.vm', '')
    //     const outputName = getOutFileName(item, module[item] as string)
    //     const className = outputName.substring(outputName.lastIndexOf('/') + 1, outputName.lastIndexOf('.'))
    //     const file: GeneratorFile = {
    //       type: item,
    //       pkg: (module.pkg + '.' + module[item]).replaceAll('{module}', moduleName.toLowerCase()),
    //       path: item,
    //       outputName,
    //       className,
    //       template: `${item}.vm`
    //     }
    //     return file
    //   })
    // }
    // console.log('module.value ---> ', module)

    const params: GeneratorData = {
      tableId: currTable.value?.id ?? '',
      // author: 'wei.yang',
      files: checkedFileTypes.value.map((fName) => fName.replace('.vm', '')),
      moduleCode: currModule.value.toString(),
      templateType: 'default',
      templateContents: []
    }
    const resp = await GeneratorApi.generator(params)
    emits('ok', resp.data, summary ?? '')
    return Promise.reject()
  }

  const currModule = ref<DictInputValues>('')

  const handleGenModuleTempChange = (value: DictInputValues | undefined) => {
    currModule.value = value ?? ''

    // GenModuleApi.getModule({ code: value }).then((resp) => {
    //   if (resp.success) {
    //     const module = resp.data
    //     const { name } = currTable.value!
    //     const modelName = camelCase(name?.substring(name?.indexOf('_') + 1))
    //     const replaceParams = {
    //       module: modelName
    //     }
    //     Object.keys(module).forEach((key) => {
    //       module[key] && (genData.value[key] = module[key]?.replace?.(/{\s*(.*?)\s*}/g, (_, key) => replaceParams[key]))
    //     })
    //     Object.keys(module).forEach((key) => {
    //       genData.value[key] = module[key]?.replace?.(/{\s*(.*?)\s*}/g, (_, key) => replaceParams[key])
    //     })
    //     formRef.value?.setFormData(genData.value)
    //   }
    // })
  }
</script>

<style scoped></style>
